import {ADMINISTRATOR, administrator} from '../../src/lib/Member'
import { errorMsg, okMsg } from '../../src/utils/socket-message'
import { Classroom, ClsMember } from "../model";

export default function(client, io) {
  // 添加 - 管理员列表
  client.on('administrator:set', function(data, cb) {
    const { members } = data;
    const { classId = ADMINISTRATOR } = data.room;
    const error = (msg) => errorMsg('administrator:set', msg);

    if (!Array.isArray(members)) {
      console.error('添加 - 管理员列表: => 用户列表不能为空!');
      return cb && cb(error('用户列表不能为空!'))
    }

    if (!classId) {
      return cb && cb(error('room 不能为空!'))
    }

    let dbClassroom = await Classroom.findOne({ where: { classId } } as any);

    if (!dbClassroom) {
      return cb && cb(error(`classId=${ classId } 的房间不存在！!`))
    }

    const dbMemberArray = []
    try {
      for (const member of members) {
        const dbMember = Object.assign(new ClsMember(), member);

        const dbDate = await dbMember.save();
        dbMemberArray.push(dbDate)
      }
    } catch (e) {
      return cb && cb(error(e))
    }

    let classMemberArray = administrator.get(classId) ?? new Map();

    for (const member of members) {
      classMemberArray.set(classId, member);
    }

    administrator.set(classId, classMemberArray);

    console.log('添加 - 管理员列表: => ', members);

    cb && cb(okMsg('administrator:get'))
  });
}
